package com.dp.mallchat.common.user.service.impl;

import com.dp.mallchat.common.common.constant.RedisKey;
import com.dp.mallchat.common.common.utils.JwtUtils;
import com.dp.mallchat.common.common.utils.RedisUtils;
import com.dp.mallchat.common.user.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author: dupeng
 * @CreateTime: 2024-05-23  19:52
 * @Description: TODO
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private JwtUtils jwtUtils;

    //token过期时间
    private static final Integer TOKEN_EXPIRE_DAYS = 5;
    //token续期时间
    private static final Integer TOKEN_RENEWAL_DAYS = 2;

    @Override
    public String getToken(Long uid) {
        String key = getLoginKey(uid);
        String token = RedisUtils.getStr(key);
        if (StringUtils.isNotBlank(token)){
            return token;
        }

        //生成用户token
        token = jwtUtils.createToken(uid);
        RedisUtils.set(key, token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }



    @Override
    public boolean verify(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return false;
        }
        //防止用户拿过期token，最新token与老token校验
        String newToken = RedisUtils.getStr(getLoginKey(uid));
        return Objects.equals(newToken,token);
    }

    @Async
    @Override
    public void renewalTokenIfNecessary(String token) {
        //token是否有效
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return;
        }
        //刷新token
        Long expireDay = RedisUtils.getExpire(getLoginKey(uid), TimeUnit.DAYS);
        if (expireDay == -2) {//不存在的key
            return;
        }
        if (expireDay < TOKEN_RENEWAL_DAYS) {
            RedisUtils.expire(getLoginKey(uid), TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        }
    }

    @Override
    public Long getValidUid(String token) {
        boolean verify = verify(token);
        return verify ? jwtUtils.getUidOrNull(token) : null;
    }

    @NotNull
    private String getLoginKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
    }
}
